package com.oxygen.pt.service.impl;
import cn.hutool.core.lang.Assert;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oxygen.pt.mapper.PressureVesselInspectionDailyMapper;
import com.oxygen.pt.pojo.dto.PressureVesselInspectionDailySaveDTO;
import com.oxygen.pt.pojo.entity.PressureVesselInspectionDaily;
import com.oxygen.pt.pojo.vo.OxygenChamberInspectionPageVO;
import com.oxygen.pt.pojo.vo.PressureVesselDailyExportVO;
import com.oxygen.pt.service.PressureVesselInspectionDailyService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;


@Service
public class PressureVesselInspectionDailyServiceImpl
        implements PressureVesselInspectionDailyService {

    @Resource
    private PressureVesselInspectionDailyMapper mapper;

    @Override
    public boolean save(PressureVesselInspectionDailySaveDTO dto) {
        return mapper.insert(dto) > 0;
    }

    @Override
    public boolean removeById(Long id) {
        return mapper.deleteById(id) > 0;
    }

    @Override
    public PressureVesselInspectionDaily getById(Long id) {
        return mapper.selectById(id);
    }

    @Override
    public boolean updateById(Long id, PressureVesselInspectionDailySaveDTO dto) {
        return mapper.updateById(id, dto) > 0;
    }

    @Override
    public PageInfo<OxygenChamberInspectionPageVO> pageOxygenChamber(String inspector,
                                                                     LocalDateTime startTime,
                                                                     LocalDateTime endTime,
                                                                     int pageNum,
                                                                     int pageSize) {
        // PageHelper 分页
        PageHelper.startPage(pageNum, pageSize);
        List<OxygenChamberInspectionPageVO> list =
                mapper.selectOxygenChamberPage(inspector, startTime, endTime);
        return new PageInfo<>(list);
    }

    /**
     * 导出压力容器日巡检记录
     *
     * @param response 响应对象
     * @param start    开始时间
     * @param end      结束时间
     * @throws IOException IO异常
     */
    public void exportExcel(HttpServletResponse response,
                            LocalDateTime start,
                            LocalDateTime end) throws IOException {
        // 参数校验
        Assert.notNull(start, "开始时间不能为空");
        Assert.notNull(end, "结束时间不能为空");
        Assert.isTrue(!start.isAfter(end), "开始时间不能晚于结束时间");

        // 查询导出数据
        List<PressureVesselDailyExportVO> exportData = mapper.listForExport(start, end);

        // 设置响应头
        setResponseHeader(response);

        // 读取模板并填充数据
        try (InputStream templateStream = getClass().getResourceAsStream("/templates/excel/daily_template.xlsx");
             ServletOutputStream outputStream = response.getOutputStream()) {

            // 验证模板是否存在
            if (templateStream == null) {
                throw new IOException("模板文件不存在: /templates/excel/daily_template.xlsx");
            }

            // 构建Excel写入器
            var writer = EasyExcel.write(outputStream)
                    .withTemplate(templateStream)
                    .autoCloseStream(false)
                    .build();

            // 配置工作表（表头在第4行，索引3）
            WriteSheet writeSheet = EasyExcel.writerSheet()
                    .relativeHeadRowIndex(3)
                    .build();

            // 执行填充
            writer.fill(exportData, writeSheet);
            writer.finish();
        }
    }

    /**
     * 设置HTTP响应头信息
     */
    private void setResponseHeader(HttpServletResponse response) throws IOException {
        String fileName = "压力容器日管控_" + LocalDate.now() + ".xlsx";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition",
                "attachment;filename=" + encodedFileName + ";filename*=UTF-8''" + encodedFileName);
        // 禁止缓存
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    }

}